<?php

$VERSION = "0.3";

/*  Lighttpd Enhanced Directory Listing Script
 *  ------------------------------------------
 *  Author: Evan Fosmark
 *  Version: 2008.08.07
 *
 *
 *  GNU License Agreement
 *  ---------------------
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *  http://www.gnu.org/licenses/gpl.txt
 */

/*  Revision by KittyKatt
 *  ---------------------
 *  E-Mail:  kittykatt@archlinux.us
 *  Website: http://www.archerseven.com/kittykatt/
 *  Version:  2010.03.01
 *
 *  Revised original code to include hiding for directories prefixed with a "." (or hidden
 *  directories) as the script was only hiding files prefixed with a "." before. Also included more
 *  file extensions/definitions.
 *
 */

$show_hidden_files = true;
$calculate_folder_size = false;

// Various file type associations
$movie_types = array('mpg','mpeg','avi','asf','mp3','wav','mp4','wma','aif','aiff','ram', 'midi','mid','asf','au','flac');
$image_types = array('jpg','jpeg','gif','png','tif','tiff','bmp','ico');
$archive_types = array('zip','cab','7z','gz','tar.bz2','tar.gz','tar','rar',);
$document_types = array('txt','text','doc','docx','abw','odt','pdf','rtf','tex','texinfo',);
$font_types = array('ttf','otf','abf','afm','bdf','bmf','fnt','fon','mgf','pcf','ttc','tfm','snf','sfd');


// Get the path (cut out the query string from the request_uri)
list($path) = explode('?', $_SERVER['REQUEST_URI']);


// Get the path that we're supposed to show.
$path = ltrim(rawurldecode($path), '/');


if(strlen($path) == 0) {
	$path = "./";
}


// Can't call the script directly since REQUEST_URI won't be a directory
if($_SERVER['PHP_SELF'] == '/'.$path) {
	die("Unable to call " . $path . " directly.");
}


// Make sure it is valid.
if(!is_dir($path)) {
	die("<b>" . $path . "</b> is not a valid path.");
}


//
// Get the size in bytes of a folder
//
function foldersize($path) {
	$size = 0;
	if($handle = @opendir($path)){
		while(($file = readdir($handle)) !== false) {
			if(is_file($path."/".$file)){
				$size += filesize($path."/".$file);
			}

			if(is_dir($path."/".$file)){
				if($file != "." && $file != "..") {
					$size += foldersize($path."/".$file);
				}
			}
		}
	}

	return $size;
}


//
// This function returns the file size of a specified $file.
//
function format_bytes($size, $precision=0) {
    $sizes = array('B', 'B', 'E', 'P', 'B', 'G', 'M', 'K', 'B');
    $total = count($sizes);

    while($total-- && $size > 1024) $size /= 1024;
    return sprintf('%.'.$precision.'f', $size).$sizes[$total];
}


//
// This function returns the mime type of $file.
//
function get_file_type($file) {
	global $image_types, $movie_types;

	$pos = strrpos($file, ".");
	if ($pos === false) {
		return "Text File";
	}

	$ext = rtrim(substr($file, $pos+1), "~");
	if(in_array($ext, $image_types)) {
		$type = "Image File";

	} elseif(in_array($ext, $movie_types)) {
		$type = "Video File";

	} elseif(in_array($ext, $archive_types)) {
		$type = "Compressed Archive";

	} elseif(in_array($ext, $document_types)) {
		$type = "Type Document";

	} elseif(in_array($ext, $font_types)) {
		$type = "Type Font";

	} else {
		$type = "File";
	}

	return(strtoupper($ext) . " " . $type);
}



// Print the heading stuff
$vpath = ($path != "./")?$path:"";
print "<!DOCTYPE html>
	<head>
		<title>Index of /" .$vpath. "</title>
		<style type='text/css'>
		a, a:active {text-decoration: none; color: blue;}
		a:visited {color: #48468F;}
		a:hover, a:focus {text-decoration: underline; color: red;}
		body {background-color: #F5F5F5;}
		h2 {margin-bottom: 12px;}
		table {margin-left: 12px;}
		th, td { font-family: monospace; font-size: 9pt; text-align: left;}
		th { font-weight: bold; padding-right: 14px; padding-bottom: 3px;}
		td {padding-right: 14px;}
		td.s, th.s {text-align: right;}
		div.list { background-color: white; border-top: 1px solid #646464; border-bottom: 1px solid #646464; padding-top: 10px; padding-bottom: 14px;}
		div.foot, div.script_title { font-family: 'Courier New', Courier, monospace; font-size: 10pt; color: #787878; padding-top: 4px;}
		div.script_title {float:right;text-align:right;font-size:8pt;color:#999;}
		</style>
	</head>
	<body>
	<h2>Index of /" . $vpath ."</h2>
	<div class='list'>
	<table summary='Directory Listing' cellpadding='0' cellspacing='0'>";




// Get all of the folders and files.
$folderlist = array();
$filelist = array();
if($handle = @opendir($path)) {
	while(($item = readdir($handle)) !== false) {
		if(is_dir($path.'/'.$item) and $item != '.' and $item != '..') {
			if( $show_hidden_files == "false" ) {
				if(substr($item, 0, 1) == "." or substr($item, -1) == "~") {
				  continue;
				}
			}
			$folderlist[] = array(
				'name' => $item,
				'size' => (($calculate_folder_size)?foldersize($path.'/'.$item):0),
				'modtime'=> filemtime($path.'/'.$item),
				'file_type' => "Directory"
			);
		}

		elseif(is_file($path.'/'.$item)) {
			if( $show_hidden_files == "false" ) {
				if(substr($item, 0, 1) == "." or substr($item, -1) == "~") {
				  continue;
				}
			}
			$filelist[] = array(
				'name'=> $item,
				'size'=> filesize($path.'/'.$item),
				'modtime'=> filemtime($path.'/'.$item),
				'file_type' => get_file_type($path.'/'.$item)
			);
		}
	}
	fclose($handle);
}

// Show sort methods
print "<thead><tr>";

$header = array();
$header['name'] = "Name";
$header['modtime'] = "Last Modified";
$header['size'] = "Size";
$header['file_type'] = "Type";

foreach($header as $key=>$item) {
	if($_GET['sort'] == $key) {
		print "<th class='n'>".$item."</th>";
	} else {
		print "<th class='n'>".$item."</th>";
	}
}
print "</tr></thead><tbody>";



// Parent directory link
if($path != "./") {
	print "<tr><td class='n'><a href='..'>..</a>/</td>";
	print "<td class='m'>&nbsp;</td>";
	print "<td class='s'>&nbsp;</td>";
	print "<td class='t'>Directory</td></tr>";
}



// Print folder information
foreach($folderlist as $folder) {
	print "<tr><td class='n'><a href='" . addslashes($folder['name']). "'>" .htmlentities($folder['name']). "</a>/</td>";
	print "<td class='m'>" . date('Y-M-d H:m:s', $folder['modtime']) . "</td>";
	print "<td class='s'>" . (($calculate_folder_size)?format_bytes($folder['size'], 2):'--') . "&nbsp;</td>";
	print "<td class='t'>" . $folder['file_type']                    . "</td></tr>";
}




// Print file information
foreach($filelist as $file) {
	print "<tr><td class='n'><a href='" . addslashes($file['name']). "'>" .htmlentities($file['name']). "</a></td>";
	print "<td class='m'>" . date('Y-M-d H:m:s', $file['modtime'])   . "</td>";
	print "<td class='s'>" . format_bytes($file['size'],2)           . "&nbsp;</td>";
	print "<td class='t'>" . $file['file_type']                      . "</td></tr>";
}


$frontend_baseurl = '{{ frontend_base_url }}';
$path = explode('/', $_SERVER['REQUEST_URI']);
if (count($path) >= 7) {
	$owner = preg_replace('/^(@|%40)(.*)$/', 'g/$2', $path[2]);
	$project = $path[3];
	$buildid = ltrim(explode('-', $path[5])[0], '0');
	$frontend_url = implode('/', [$frontend_baseurl, 'coprs', $owner, $project, 'build', $buildid]);
	$frontend_url_text = 'Go to COPR frontend build';
} else if (count($path) >= 5) {
	$owner = preg_replace('/^(@|%40)(.*)$/', 'g/$2', $path[2]);
	$project = $path[3];
	$frontend_url = implode('/', [$frontend_baseurl, 'coprs', $owner, $project]);
	$frontend_url_text = 'Go to COPR frontend project';
} else {
	$frontend_url = $frontend_baseurl;
	$frontend_url_text = 'Go to COPR frontend';
}

// Print ending stuff
print "</tbody>
	</table>
	</div>
	<div class='script_title'>Lighttpd Enhanced Directory Listing Script</div>
	<div class='script_title' style='float:left; font-size:10pt'><a href=".$frontend_url.">".$frontend_url_text."</a></div>
	<div class='foot'>". $_ENV['SERVER_SOFTWARE'] . "</div>
	<script type='text/javascript'>
	// <!--

	var click_column;
	var name_column = 0;
	var date_column = 1;
	var size_column = 2;
	var type_column = 3;
	var prev_span = null;

	if (typeof(String.prototype.localeCompare) === 'undefined') {
	 String.prototype.localeCompare = function(str, locale, options) {
	   return ((this == str) ? 0 : ((this > str) ? 1 : -1));
	 };
	}

	if (typeof(String.prototype.toLocaleUpperCase) === 'undefined') {
	 String.prototype.toLocaleUpperCase = function() {
	  return this.toUpperCase();
	 };
	}

	function get_inner_text(el) {
	 if((typeof el == 'string')||(typeof el == 'undefined'))
	  return el;
	 if(el.innerText)
	  return el.innerText;
	 else {
	  var str = '';
	  var cs = el.childNodes;
	  var l = cs.length;
	  for (i=0;i<l;i++) {
	   if (cs[i].nodeType==1) str += get_inner_text(cs[i]);
	   else if (cs[i].nodeType==3) str += cs[i].nodeValue;
	  }
	 }
	 return str;
	}

	function isdigit(c) {
	 return (c >= '0' && c <= '9');
	}

	function unit_multiplier(unit) {
	 return (unit=='K') ? 1000
	      : (unit=='M') ? 1000000
	      : (unit=='G') ? 1000000000
	      : (unit=='T') ? 1000000000000
	      : (unit=='P') ? 1000000000000000
	      : (unit=='E') ? 1000000000000000000 : 1;
	}

	function sortfn_then_by_name(a,b,sort_column) {
	 if (sort_column == name_column || sort_column == type_column) {
	  var ad = (a.cells[type_column].innerHTML === 'Directory');
	  var bd = (b.cells[type_column].innerHTML === 'Directory');
	  if (ad != bd) return (ad ? -1 : 1);
	 }
	 var at = get_inner_text(a.cells[sort_column]);
	 var bt = get_inner_text(b.cells[sort_column]);
	 var cmp;
	 if (a.cells[sort_column].className == 'int') {
	  cmp = parseInt(at)-parseInt(bt);
	 } else if (sort_column == date_column) {
	  cmp = Date.parse(at.replace(/-/g, '/'))
	      - Date.parse(bt.replace(/-/g, '/'));
	  var ad = isdigit(at.substr(0,1));
	  var bd = isdigit(bt.substr(0,1));
	  if (ad != bd) return (!ad ? -1 : 1);
	 } else if (sort_column == size_column) {
	  var ai = parseInt(at, 10) * unit_multiplier(at.substr(-1,1));
	  var bi = parseInt(bt, 10) * unit_multiplier(bt.substr(-1,1));
	  if (at.substr(0,1) == '-') ai = -1;
	  if (bt.substr(0,1) == '-') bi = -1;
	  cmp = ai - bi;
	 } else {
	  cmp = at.toLocaleUpperCase().localeCompare(bt.toLocaleUpperCase());
	  if (0 != cmp) return cmp;
	  cmp = at.localeCompare(bt);
	 }
	 if (0 != cmp || sort_column == name_column) return cmp;
	 return sortfn_then_by_name(a,b,name_column);
	}

	function sortfn(a,b) {
	 return sortfn_then_by_name(a,b,click_column);
	}

	function resort(lnk) {
	 var span = lnk.childNodes[1];
	 var table = lnk.parentNode.parentNode.parentNode.parentNode;
	 var rows = new Array();
	 for (j=1;j<table.rows.length;j++)
	  rows[j-1] = table.rows[j];
	 click_column = lnk.parentNode.cellIndex;
	 rows.sort(sortfn);

	 if (prev_span != null) prev_span.innerHTML = '';
	 if (span.getAttribute('sortdir')=='down') {
	  span.innerHTML = '&uarr;';
	  span.setAttribute('sortdir','up');
	  rows.reverse();
	 } else {
	  span.innerHTML = '&darr;';
	  span.setAttribute('sortdir','down');
	 }
	 for (i=0;i<rows.length;i++)
	  table.tBodies[0].appendChild(rows[i]);
	 prev_span = span;
	}

	function init_sort(init_sort_column, ascending) {
	 var tables = document.getElementsByTagName('table');
	 for (var i = 0; i < tables.length; i++) {
	  var table = tables[i];
	  //var c = table.getAttribute('class')
	  //if (-1 != c.split(' ').indexOf('sort')) {
	   var row = table.rows[0].cells;
	   for (var j = 0; j < row.length; j++) {
	    var n = row[j];
	    if (n.childNodes.length == 1 && n.childNodes[0].nodeType == 3) {
	     var link = document.createElement('a');
	     var title = n.childNodes[0].nodeValue.replace(/:$/, '');
	     link.appendChild(document.createTextNode(title));
	     link.setAttribute('href', '#');
	     link.setAttribute('class', 'sortheader');
	     link.setAttribute('onclick', 'resort(this);return false;');
	     var arrow = document.createElement('span');
	     arrow.setAttribute('class', 'sortarrow');
	     arrow.appendChild(document.createTextNode(':'));
	     link.appendChild(arrow)
	     n.replaceChild(link, n.firstChild);
	    }
	   }
	   var lnk = row[init_sort_column].firstChild;
	   if (ascending) {
	    var span = lnk.childNodes[1];
	    span.setAttribute('sortdir','down');
	   }
	   resort(lnk);
	  //}
	 }
	}

	init_sort(0, 0);

	// -->
	</script>

	</body>
	</html>";


/* -------------------------------------------------------------------------------- *\
	I hope you enjoyed my take on the enhanced directory listing script!
	If you have any questions, feel free to contact me.

	Regards,
	   Evan Fosmark < me@evanfosmark.com >
\* -------------------------------------------------------------------------------- */
?>
